package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.common.dtas.BaseServiceImpl;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WemediaLoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WemediaLoginServiceImpl extends BaseServiceImpl<WmUserMapper, WmUser> implements WemediaLoginService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.检查参数
        if (dto==null|| StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword()))return ErrorParam;

        WmUser wmUser = getOne(new QueryWrapper<WmUser>().lambda().eq(WmUser::getName, dto.getName()));
        if (wmUser==null)return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"用户不存在");
        String wmUserPassword = wmUser.getPassword();//表里的密码
        String psw= DigestUtils.md5DigestAsHex((dto.getName()+wmUser.getSalt()).getBytes());
        if (wmUserPassword.equals(psw)){
            Map<String, Object> hashMap = new HashMap<>();
            wmUser.setPassword("");
            wmUser.setSalt("");
            hashMap.put("wmUser",wmUser);
            hashMap.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
            return ResponseResult.okResult(hashMap);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户或密码错误");
    }
}
